package com.example.qt.ptplatform.controller;
import com.example.qt.ptplatform.service.impl.UserServiceImpl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import com.example.qt.ptplatform.service.impl.DownloadServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.example.qt.ptplatform.utils.JsonResult;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping(value = "download")
public class DownloadController {

    @Autowired
    private DownloadServiceImpl downloadService;
    @Autowired
    private UserServiceImpl userService;

    @GetMapping("/getfile")
    public ResponseEntity<InputStreamResource> downloadFile(@RequestParam("user_id") Integer userId,
                                                            @RequestParam("torrent_id") Integer torrentId) {
        try {
            userService.updateLikedTorrentsAndTags(userId, torrentId, "download");
            // 调用服务层方法下载文件并返回结果
            JsonResult jsonResult = downloadService.downloadTorrent(userId, torrentId);

            if (!jsonResult.getResult()) {
                return ResponseEntity.badRequest().body(null); // 如果失败，返回失败响应
            }

            File file = (File) jsonResult.getRows(); // 获取文件对象
            FileInputStream fileInputStream = new FileInputStream(file);

            // 构造文件下载的HTTP响应
            InputStreamResource resource = new InputStreamResource(fileInputStream);
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .contentLength(file.length())
                    .body(resource);
        } catch (IOException e) {
            return ResponseEntity.status(500).body(null); // 服务器内部错误
        }
    }

    @GetMapping("/records")
    public JsonResult getDownloadRecords(@RequestParam("user_id") Integer userId,
                                         @RequestParam("page") Integer page,
                                         @RequestParam("per_page") Integer perPage) {
        // 调用服务层获取下载记录并返回分页结果
        return downloadService.getDownloadRecords(userId, page, perPage);
    }

    // 删除下载记录
    @DeleteMapping("/deleteRecords")
    public JsonResult deleteDownloadRecord(@RequestParam("user_id") Integer userId,
                                           @RequestParam("download_id") Integer downloadId) {
        // 调用服务层方法删除记录
        return downloadService.deleteDownloadRecord(userId, downloadId);
    }

}
